<?php


namespace app\platform\system\controller;

use app\common\controller\BaseController;
use app\common\model\SysAdmin;
use app\platform\system\service\AdminService;
use app\platform\system\validate\AdminLoginValidate;
use common\event\EventConst;
use support\exception\BadException;
use support\utils\RandomUtil;
use support\utils\Time;
use support\utils\UserUtil;
use think\facade\Db;
use Webman\Event\Event;

class LoginController extends BaseController
{
    protected array $noNeedLogin = [
        'login',
    ];

    public function login()
    {
        AdminLoginValidate::goCheck(input());

        $username = input('username');
        $password = input('password');
        $user = SysAdmin::where([
            'username' => $username
        ])->field(['id', 'password', 'salt', 'status'])->find();

        if ($user['status'] != 0) {
            throw new BadException("账号已经被禁用");
        }
        if (!$user) {
            throw new BadException("账号密码错误");
        }
        if (!AdminService::checkPassword($password, $user['password'], $user['salt'])) {
            throw new BadException("账号密码错误");
        }

        $token = md5($username . $password . RandomUtil::randomStr());
        $user->token = $token;
        $user->ip = request()->getRealIp();
        $user->login_time = Time::now();
        $user->save();
        $data = [
            'uid' => $user['id'],
            'token' => $token,
            'username' => $username,
            'ip' => $user->ip,
            'time' => $user->login_time,
            'os' => request()->os,
        ];
        Event::emit(EventConst::USER_LOGIN, [
            'uid' => $user['id'],
            'token' => $token,
            'username' => $username,
            'ip' => $user->ip,
            'time' => $user->login_time,
            'os' => request()->os,
        ]);
        return $this->success([
            "tokenName" => "Authorization",
            'tokenValue' => $token
        ]);
    }

    public function loginOut()
    {
        Db::table(SysAdmin::getTable())->where([
            "id" => UserUtil::getUid()
        ])->update([
            "token" => ""
        ]);
        return $this->success();
    }

}